﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Security.Principal;
using System.Net;

namespace SimpleMVC.Filters
{
    public class GlobalAuthenticationFilter: IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.IsChildAction)
            {
                return;
            }
            var session = filterContext.RequestContext.HttpContext.Session;
            if (session != null && session["user"] != null && session["roles"] != null)
            {
                string name = session["user"].ToString();
                string[] roles = session["roles"] as string[];
                filterContext.Principal = new GenericPrincipal(new GenericIdentity(name), roles);
            }
            else
            {
                return;
            }
        }
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            filterContext.Result = new SessionChallengeResult() { currentResult = filterContext.Result };
        }
    }
}